import React from 'react';
import { Image, StyleSheet, Text, TextInput, TouchableOpacity, View, } from 'react-native';

import Spinner from 'react-native-loading-spinner-overlay'

import Constant from '../Constant/Constant'
import ScreenUtils from '../Utils/ScreenUtils'
import ColorUtils from '../Utils/ColorUtils'
import ToastUtils from '../Utils/ToastUtils'
import HttpUtils from '../Utils/HttpUtils'
import RuleUtils from '../Utils/RuleUtils'
import RouterUtils from '../Utils/RouterUtils'
import TimeUtils from '../Utils/TimeUtils'

export default class UserFindPassword extends React.Component
{
    static navigationOptions = ({navigation}) => ({
        gesturesEnabled: false,//是否支持滑动返回收拾，iOS默认支持，安卓默认关闭
        headerTitle: '忘记密码',
        headerStyle: {
            backgroundColor: ColorUtils.blue,
            height: ScreenUtils.statusBarHeight,
        },
        headerRight: (<Text></Text>),
        headerTintColor: ColorUtils.white,
        headerTitleStyle: {
            fontSize: ScreenUtils.Font_18,
            color: ColorUtils.white,
            fontWeight: 'normal',
            flex: 1,
            alignSelf: 'center',
            textAlign: 'center',
        }
    });

    constructor(props)
    {
        super(props);
        this.state = {
            loading: false,
            timerCount: 60,
            timerTitle: '获取验证码',
            isFinish: true,
            phone: '',
            authcode: '',
            newpwd: '',
        };
    }

    componentDidMount()
    {
        RouterUtils.pushRouter('UserFindPassword', this.props.navigation.state.key);
    }

    componentWillUnmount()
    {
        RouterUtils.popRouter('UserFindPassword', this.props.navigation.state.key);
    }

    countDown()
    {
        this.getSmsCode();
    }

    getSmsCode()
    {
        try
        {
            RuleUtils.checkPhoneRegex(this.state.phone);
            var data = {'appId': Constant.appId, 'phone': this.state.phone, 'timeStamp': TimeUtils.getCurrentDate()};
            HttpUtils.postJson(Constant.getForgetPwdAuthCode, data, this.getSmsCodeSuccess.bind(this), this.getSmsCodeError.bind(this));
        }
        catch (error)
        {
            ToastUtils.toastShortBottom(error);
        }
    }

    getSmsCodeSuccess(result)
    {
        ToastUtils.toastShortBottom('短信验证码发送成功');
        this.interval = setInterval(() =>
        {
            const timer = this.state.timerCount - 1
            if (timer <= 0)
            {
                this.interval && clearInterval(this.interval);
                this.setState({
                    timerCount: 60,
                    isFinish: true
                })
            } else
            {
                this.setState({
                    timerCount: timer,
                    isFinish: false,
                })
            }
        }, 1000)
    }

    getSmsCodeError(opcode, reason)
    {
        ToastUtils.toastShortCenter('短信验证码发送失败,错误码:' + opcode);
    }

    findPasswordSuccess(result)
    {
        this.setState({
            loading: false
        })
        ToastUtils.toastShortBottom('重置密码成功');
        this.props.navigation.goBack();
    }

    findPasswordError(opcode, reason)
    {
        this.setState({
            loading: false
        })
        if (opcode == '4')
        {
            ToastUtils.toastShortBottom('手机号已被注册');
        }
        if (opcode == '5')
        {
            ToastUtils.toastShortBottom('用户名已被注册');
        }
        if (opcode == '6')
        {
            ToastUtils.toastShortBottom('验证码错误');
        }
    }

    findPassword()
    {
        try
        {
            RuleUtils.checkPhoneRegex(this.state.phone);
            RuleUtils.checkSMSCodeRegex(this.state.authcode);
            RuleUtils.checkPwdValid(this.state.newpwd);
            this.setState({
                loading: true
            })
            var data = {'appId': Constant.appId, 'phone': this.state.phone, 'authcode': this.state.authcode, 'newpwd': this.state.newpwd, 'timeStamp': TimeUtils.getCurrentDate()};
            HttpUtils.postJson(Constant.resetPwd, data, this.findPasswordSuccess.bind(this), this.findPasswordError.bind(this));
        }
        catch (error)
        {
            ToastUtils.toastShortBottom(error);
        }
    }

    renderSmsCodeView()
    {
        if (this.state.isFinish)
        {
            return <TouchableOpacity onPress={() => this.countDown()}>
                <View style={{height: 40, padding: 8, justifyContent: 'center', alignItems: 'center', borderLeftWidth: 1, borderLeftColor: '#DADADA'}}>
                    <Text style={{color: ColorUtils.blue}}>获取验证码</Text>
                </View>
            </TouchableOpacity>;
        } else
        {
            return <View style={{height: 40, padding: 8, justifyContent: 'center', alignItems: 'center', borderLeftWidth: 1, borderLeftColor: '#DADADA'}}>
                <Text style={{color: ColorUtils.gray}}>{'重新获取(' + this.state.timerCount + ')'}</Text>
            </View>
        }
    }

    render()
    {
        return (
            <View style={styles.container}>
                <View style={{padding: 16,}}>
                    <Text style={{fontSize: ScreenUtils.Font_24, color: ColorUtils.black}}>账号验证</Text>
                    <Text style={{marginTop: 8, fontSize: ScreenUtils.Font_14, color: ColorUtils.light_gray}}>输入手机号及验证码</Text>
                </View>
                {/*<Spinner visible={this.state.loading} size={Spinner.normal} cancelable={true} color={ColorUtils.green}/>*/}
                <View style={{marginTop: 16, marginLeft: 16, marginRight: 16, borderColor: '#DADADA', borderWidth: 1, borderRadius: 4}}>
                    <View style={{height: 40, flexDirection: 'row', borderBottomWidth: 1, borderBottomColor: '#DADADA', alignItems: 'center'}}>
                        <Image source={require('../img/phone.png')} style={{marginLeft: 8, marginRight: 8, width: 20, height: 20}}/>
                        <TextInput underlineColorAndroid='transparent' keyboardType='numeric' maxLength={11} placeholder='请输入手机号' onChangeText={(text) => this.setState({phone: text})} multiline={false}
                                   style={{fontSize: ScreenUtils.Font_14, flex: 1, height: 40, marginLeft: 4}}/>
                    </View>
                    <View style={{height: 40, flexDirection: 'row', borderBottomWidth: 1, borderBottomColor: '#DADADA', alignItems: 'center'}}>
                        <Image source={require('../img/sms.png')} style={{marginLeft: 8, marginRight: 8, width: 20, height: 20}}/>
                        <TextInput underlineColorAndroid='transparent' keyboardType='numeric' maxLength={6} placeholder='请输入短信验证码' onChangeText={(text) => this.setState({authcode: text})} multiline={false}
                                   style={{fontSize: ScreenUtils.Font_14, flex: 1, height: 40, marginLeft: 4}}/>
                        {this.renderSmsCodeView()}
                    </View>
                    <View style={{height: 40, flexDirection: 'row', alignItems: 'center'}}>
                        <Image source={require('../img/password.png')} style={{marginLeft: 8, marginRight: 8, width: 20, height: 20}}/>
                        <TextInput underlineColorAndroid='transparent' secureTextEntry={true} keyboardType='default' maxLength={20} placeholder='请输入重置密码' onChangeText={(text) => this.setState({newpwd: text})}
                                   multiline={false} style={{fontSize: ScreenUtils.Font_14, flex: 1, height: 40, marginLeft: 4}}/>
                    </View>
                </View>
                <View style={{margin: 32}}>
                    <TouchableOpacity onPress={() => this.findPassword()}>
                        <View style={{justifyContent: 'center', alignItems: 'center', height: 44, padding: 4, borderRadius: 6, backgroundColor: ColorUtils.blue}}>
                            <Text style={{color: ColorUtils.white, fontSize: ScreenUtils.Font_14}}>
                                重置密码
                            </Text>
                        </View>
                    </TouchableOpacity>
                </View>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: ColorUtils.white,
    },
});


